package rs2.consultoria.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;

import rs2.consultoria.dao.GenericDaoInterface;

/**
 * Classe DAO genérica contendo os principais métodos comuns aos DAOs derivados.
 * 
 * @author Diego Dias
 */
public abstract class GenericDaoImpl<T extends Serializable> implements
		GenericDaoInterface<T> {

	protected Class<T> classeEntidade;

	@Inject
	protected EntityManager em;

	@SuppressWarnings("unchecked")
	public GenericDaoImpl() {
		ParameterizedType genericSuperclass = (ParameterizedType) getClass()
				.getGenericSuperclass();
		this.classeEntidade = (Class<T>) genericSuperclass
				.getActualTypeArguments()[0];
	}

	@Override
	public T retornarPorId(final long id) {
		return em.find(classeEntidade, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> retornarTodos() {
		List<T> resultList = em.createQuery("FROM " + classeEntidade.getName())
				.getResultList();
		return resultList;
	}

	@Override
	public void salvar(T entity) {
		em.persist(entity);
	}

	@Override
	public T mesclar(T entity) {
		return em.merge(entity);
	}

	@Override
	public void remover(T entity) {
		em.remove(entity);
	}

	@Override
	public void removerPorId(final long id) {
		T entity = retornarPorId(id);
		remover(entity);
	}


}